<template>
    <div class="XSwitch" :class="{ 'XSwitch--small': small }">
        <div @click="change(false)">
            {{ leftText }}
        </div>
        <div class="toggle-switch" :class="{ 'toggle-switch--checked': isChecked }" @click="toggle">
            <div class="toggle-switch__slider"></div>
        </div>
        <div @click="change(true)">
            {{ rightText }}
        </div>
    </div>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch } from 'vue'

const props = defineProps({
    // 值
    modelValue: {
        type: Boolean,
        default: false
    },
    // 改变时的回调
    onChange: {
        type: Function,
        default: null
    },
    rightText: {
        type: String,
        default: '开'
    },
    leftText: {
        type: String,
        default: '关'
    },
    small: {
        type: Boolean,
        default: false
    }
})
const emit = defineEmits(['update:modelValue'])
const isChecked = ref(props.modelValue)
const toggle = () => {
    isChecked.value = !isChecked.value
    emit('update:modelValue', isChecked.value)
    if (props.onChange) {
        props.onChange(isChecked.value)
    }
}
const change = (val) => {
    if (isChecked.value !== val) {
        isChecked.value = val
        emit('update:modelValue', isChecked.value)
        if (props.onChange) {
            props.onChange(isChecked.value)
        }
    }
}
watch(
    () => props.modelValue,
    (newVal) => {
        isChecked.value = newVal
    }
)
</script>

<style scoped lang="scss">
.XSwitch {
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    font-size: 21px;

    /* 默认样式 */
    .toggle-switch {
        display: flex;
        align-items: center;
        cursor: pointer;
        width: 50px;
        height: 25px;
        margin: 0 6px;
        background-color: #ccc;
        border-radius: 20px;
        position: relative;
        transition: background-color 0.3s;
        box-shadow: inset 0 0 5px #fff3;
        border: 1px solid #666;

        .toggle-switch__slider {
            width: 23px;
            height: 23px;
            background-color: #777;
            border-radius: 50%;
            position: absolute;
            top: 1px;
            transition: transform 0.3s;
            transform: translateX(1px);
        }
    }

    /** 选中样式 */
    .toggle-switch--checked {
        background-color: #eee;
        .toggle-switch__slider {
            transform: translateX(26px);
        }
    }
}

/**small样式 */
.XSwitch--small {
    font-size: 17px;
    .toggle-switch {
        width: 35px;
        height: 18px;
        .toggle-switch__slider {
            width: 16px;
            height: 16px;
            transform: translateX(1px);
        }
    }
    /** 选中样式 */
    .toggle-switch--checked {
        .toggle-switch__slider {
            transform: translateX(18px);
        }
    }
}
</style>
